﻿using MesForm.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace MesForm
{
    public partial class frmForm : Form
    {
        /// <summary>
        /// 基本路径
        /// </summary>
        public string BasePath = AppDomain.CurrentDomain.BaseDirectory;
        /// <summary>
        /// Mes参数集
        /// </summary>
        private XmlDocument _mesParamOC = null;
        public frmForm()
        {
            InitializeComponent();
            BeautifyControls();
        }
        private void BeautifyControls()
        {
            foreach (Control control in this.Controls)
            {
                control.Font = new Font("Arial", 10, FontStyle.Regular);
                control.BackColor = Color.LightBlue;
                control.ForeColor = Color.DarkBlue;
                if (control is Button button)
                {
                    button.FlatStyle = FlatStyle.Flat;
                    button.FlatAppearance.BorderSize = 1;
                    button.FlatAppearance.BorderColor = Color.DarkBlue;
                }
                else if (control is TextBox textBox)
                {
                    textBox.BorderStyle = BorderStyle.FixedSingle;
                }
                else if (control is ComboBox comboBox)
                {
                    comboBox.FlatStyle = FlatStyle.Flat;
                }
                else if (control is DataGridView dataGridView)
                {
                    dataGridView.BackgroundColor = Color.LightBlue;
                    dataGridView.DefaultCellStyle.BackColor = Color.White;
                    dataGridView.DefaultCellStyle.ForeColor = Color.DarkBlue;
                    dataGridView.ColumnHeadersDefaultCellStyle.BackColor = Color.DarkBlue;
                    dataGridView.ColumnHeadersDefaultCellStyle.ForeColor = Color.White;
                }
            }
        }
        /// <summary>
        /// MesConfig参数加载初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmForm_Load(object sender, EventArgs e)
        {
            CheckMesParamOC();
            LoadMesInterface();
            LoadXmlDataToAllDataGridViews();
            string json2 = "{\r\n\t\"userNo\": \"1809110053\",\r\n\t\"passWord\": \"a.123456\",\r\n\t\"deviceSn\": \"Ls0001\",\r\n\t\"moNumber\": \"MO001122\",\r\n\t\"groupCode\": \"JR\",\r\n    \"timeStamp\": \"2021-10-27 14:22:33\"\r\n}".Replace("\r\n", "").Replace(" ", "");
            string json = "{\r\n    \"groupCode\": \"SubCapacity\",\r\n    \"deviceSn\": \"L2CAPAC019\",\r\n    \"timeStamp\": \"2018-01-0110:10:00\",\r\n    \"operatorId\": \"63462\",\r\n    \"productSn\": \"06TCEA1N01L01H8310032761\",\r\n    \"moNumber\": \"Test20181218-1401\",\r\n    \"testResult\": \"0\",\r\n    \"testData\": [\r\n        {\r\n            \"paramCode\": \"1001\",\r\n            \"paramName\": \"电芯编码与托盘码绑定信息\",\r\n            \"paramValue\": \"A123456\",\r\n            \"paramResult\": \"0\",\r\n\"paramUnit\": \"mm\"\r\n\r\n        },\r\n        {\r\n            \"paramCode\": \"1001\",\r\n            \"paramName\": \"电芯编码与托盘码绑定信息\",\r\n            \"paramValue\": \"A123456\",\r\n            \"paramResult\": \"0\",\r\n\"paramUnit\": \"mm\"\r\n        }\r\n    ],\r\n    \"environment\": [\r\n        {\r\n\"paramCode\": \"1001\",\r\n            \"paramName\": \"温度\",\r\n            \"paramValue\": \"12\",\r\n            \"paramResult\": \"0\",\r\n\"paramUnit\": \"mm\"\r\n\r\n        },\r\n        {\r\n\"paramCode\": \"1001\",\r\n            \"paramName\": \"温度\",\r\n            \"paramValue\": \"12\",\r\n            \"paramResult\": \"0\",\r\n\"paramUnit\": \"mm\"\r\n\r\n        }\r\n    ],\r\n    \"stepData\": [\r\n        {\r\n            \"trayNo\": \"HB041602\",\r\n            \"channelNo\": \"1\",\r\n            \"batchNo\": \"1\",\r\n            \"step\": \"1\",\r\n            \"stepName\": \"搁置\",\r\n            \"startDate\": \"2018-11-2203:48:18\",\r\n            \"endDate\": \"2018-11-2203:49:07\",\r\n            \"circulatingNumber\": \"1\",\r\n            \"turnTime\": \"60\",\r\n            \"endElectricity\": \"0.0003\",\r\n            \"capacity\": \"0\",\r\n            \"energy\": \"0\",\r\n            \"constantCurrent\": \"0\",\r\n            \"startVol\": \"3.6663\",\r\n            \"midVol\": \"3.6663\",\r\n            \"endVol\": \"3.6663\",\r\n            \"chargeElectricity\": \"0\",\r\n            \"marking\": \"欣旺达现场结果\",\r\n            \"avgvol\": \"3.66632\",\r\n            \"endTemperature\": \"23.2\",\r\n            \"upLoadPath\": \"\",\r\n            \"maxHousetemp\": \"\",\r\n            \"minHousetemp\": \"\",\r\n            \"maxCellTemperature\": \"\",\r\n            \"minCellTemperature\": \"\",\r\n            \"startCellTemperature\": \"\",\r\n            \"endCellTemperature\": \"\",\r\n            \"startFirstHousetemp\": \"\",\r\n            \"endFirstHousetemp\": \"\",\r\n            \"startAfterHousetemp\": \"\",\r\n            \"endAfterHousetemp\": \"\"\r\n        },\r\n        {\r\n            \"trayNo\": \"HB041602\",\r\n            \"channelNo\": \"1\",\r\n            \"batchNo\": \"1\",\r\n            \"step\": \"2\",\r\n            \"stepName\": \"搁置\",\r\n            \"startDate\": \"2018-11-2203:48:18\",\r\n            \"endDate\": \"2018-11-2203:49:07\",\r\n            \"circulatingNumber\": \"1\",\r\n            \"turnTime\": \"60\",\r\n            \"endElectricity\": \"0.0003\",\r\n            \"capacity\": \"0\",\r\n            \"energy\": \"0\",\r\n            \"constantCurrent\": \"0\",\r\n            \"startVol\": \"3.6663\",\r\n            \"midVol\": \"3.6663\",\r\n            \"endVol\": \"3.6663\",\r\n            \"chargeElectricity\": \"0\",\r\n            \"marking\": \"欣旺达现场结果\",\r\n            \"avgvol\": \"3.66632\",\r\n            \"endTemperature\": \"23.2\",\r\n            \"upLoadPath\": \"\",\r\n            \"maxHousetemp\": \"\",\r\n            \"minHousetemp\": \"\",\r\n            \"maxCellTemperature\": \"\",\r\n            \"minCellTemperature\": \"\",\r\n            \"startCellTemperature\": \"\",\r\n            \"endCellTemperature\": \"\",\r\n            \"startFirstHousetemp\": \"\",\r\n            \"endFirstHousetemp\": \"\",\r\n            \"startAfterHousetemp\": \"\",\r\n            \"endAfterHousetemp\": \"\"\r\n        }\r\n    ]\r\n}\r\n".Replace("\r\n", "").Replace(" ", "");
        }
        /// <summary>
        /// 加载MES接口
        /// </summary>
        private void LoadMesInterface()
        {
            foreach (XmlNode MesParamNode in _mesParamOC.SelectNodes("MesConfig/System"))
            {
                txtEquipPC_ID.Text = MesParamNode.SelectSingleNode("loginUser").InnerText.Trim().Replace("/r/n", System.Environment.NewLine);
                txtEquip_PassWord.Text = MesParamNode.SelectSingleNode("loginPassword").InnerText.Trim().Replace("/r/n", System.Environment.NewLine);
                txtRmtAddress.Text = MesParamNode.SelectSingleNode("loginUrl").InnerText.Trim().Replace("/r/n", System.Environment.NewLine);
            }
        }
        /// <summary>
        /// 检查Mes参数集
        /// </summary>
        private void CheckMesParamOC()
        {
            string errStr = string.Empty;
            string filePath = BasePath + "Config\\MesParamConfig.xml";
            //Mes参数集为空,需要从文件加载Mes参数
            if (_mesParamOC == null)
            {
                try
                {
                    XmlDocument xmlDocument = new XmlDocument();
                    xmlDocument.Load(filePath);
                    _mesParamOC = xmlDocument;
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
        /// <summary>
        /// 加载接口参数集
        /// </summary>
        private void LoadXmlDataToAllDataGridViews()
        {
            try
            {
                // 获取所有 MesModel 节点
                XmlNodeList mesModelNodes = _mesParamOC.SelectNodes("//MesModel");

                // 遍历 TabControl 的每个 TabPage
                foreach (TabPage tabPage in tabControl1.TabPages)
                {
                    // 查找每个 TabPage 中的 DataGridView
                    foreach (Control control in tabPage.Controls)
                    {
                        if (control is DataGridView dataGridView)
                        {
                            // 清空 DataGridView 原有数据
                            dataGridView.Rows.Clear();

                            // 获取当前 DataGridView 的列名
                            string paramNameColumn = dataGridView.Columns[0].Name; // 参数名列
                            string paramValueColumn = dataGridView.Columns[1].Name; // 参数值列

                            // 遍历每个 MesModel 节点
                            foreach (XmlNode mesModelNode in mesModelNodes)
                            {
                                // 获取 MesModel 的属性
                                string name = mesModelNode.Attributes["name"].Value;
                                string cnName = mesModelNode.Attributes["cnName"].Value;

                                // 获取 SendData 节点
                                XmlNode sendDataNode = mesModelNode.SelectSingleNode("SendData");
                                if (sendDataNode != null && name == tabPage.Tag?.ToString())
                                {
                                    // 遍历 SendData 下的所有子节点
                                    foreach (XmlNode sendDataChildNode in sendDataNode.ChildNodes)
                                    {
                                        if (sendDataChildNode.NodeType == XmlNodeType.Element)
                                        {
                                            if (sendDataChildNode.Name == "testData" || sendDataChildNode.Name == "environment" || sendDataChildNode.Name == "stepData")
                                            {
                                                // 处理包含多个 <item> 的节点
                                                foreach (XmlNode itemNode in sendDataChildNode.ChildNodes)
                                                {
                                                    if (itemNode.NodeType == XmlNodeType.Element && itemNode.Name == "item")
                                                    {
                                                        // 遍历 <item> 的子节点
                                                        foreach (XmlNode fieldNode in itemNode.ChildNodes)
                                                        {
                                                            if (fieldNode.NodeType == XmlNodeType.Element)
                                                            {
                                                                string paramName = $"{sendDataChildNode.Name}.{fieldNode.Name}";
                                                                string paramValue = fieldNode.InnerText;
                                                                AddRowToDataGridView(dataGridView, paramNameColumn, paramValueColumn, paramName, paramValue);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                string paramName = sendDataChildNode.Name;
                                                string paramValue = sendDataChildNode.InnerText;
                                                AddRowToDataGridView(dataGridView, paramNameColumn, paramValueColumn, paramName, paramValue);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void AddRowToDataGridView(DataGridView dataGridView, string paramNameColumn, string paramValueColumn, string paramName, string paramValue)
        {
            int newRowIndex = dataGridView.Rows.Add();
            dataGridView.Rows[newRowIndex].Cells[paramNameColumn].Value = paramName;
            dataGridView.Rows[newRowIndex].Cells[paramValueColumn].Value = paramValue;
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                // 保存 System 节点数据
                XmlNode systemNode = _mesParamOC.SelectSingleNode("MesConfig/System");
                if (systemNode != null)
                {
                    UpdateXmlNode(systemNode, "loginUrl", txtRmtAddress.Text.Trim());
                    //UpdateXmlNode(systemNode, "loginTime", txtRetryTimes.Text.Trim());
                    UpdateXmlNode(systemNode, "loginUser", txtEquipPC_ID.Text.Trim());
                    UpdateXmlNode(systemNode, "loginPassword", txtEquip_PassWord.Text.Trim());
                }

                // 清空原有的 SendData 节点数据
                XmlNodeList mesModelNodes = _mesParamOC.SelectNodes("//MesModel");
                foreach (XmlNode mesModelNode in mesModelNodes)
                {
                    XmlNode sendDataNode = mesModelNode.SelectSingleNode("SendData");
                    if (sendDataNode != null)
                    {
                        sendDataNode.RemoveAll();
                    }
                }

                // 遍历 TabControl 的每个 TabPage
                foreach (TabPage tabPage in tabControl1.TabPages)
                {
                    // 查找每个 TabPage 中的 DataGridView
                    foreach (Control control in tabPage.Controls)
                    {
                        if (control is DataGridView dataGridView)
                        {
                            // 获取当前 DataGridView 的列名
                            string paramNameColumn = dataGridView.Columns[0].Name; // 参数名列
                            string paramValueColumn = dataGridView.Columns[1].Name; // 参数值列

                            // 找到对应的 MesModel 节点
                            XmlNode mesModelNode = _mesParamOC.SelectSingleNode($"//MesModel[@name='{tabPage.Tag}']");
                            if (mesModelNode != null)
                            {
                                XmlNode sendDataNode = mesModelNode.SelectSingleNode("SendData");
                                if (sendDataNode == null)
                                {
                                    sendDataNode = _mesParamOC.CreateElement("SendData");
                                    mesModelNode.AppendChild(sendDataNode);
                                }

                                // 用于临时存储 <item> 数据
                                Dictionary<string, XmlNode> itemNodes = new Dictionary<string, XmlNode>();

                                // 遍历 DataGridView 的每一行
                                foreach (DataGridViewRow row in dataGridView.Rows)
                                {
                                    if (!row.IsNewRow)
                                    {
                                        string paramName = row.Cells[paramNameColumn].Value?.ToString();
                                        string paramValue = row.Cells[paramValueColumn].Value?.ToString();

                                        if (!string.IsNullOrEmpty(paramName) && paramName.Contains("."))
                                        {
                                            string[] parts = paramName.Split('.');
                                            string parentNodeName = parts[0]; // testData, environment, stepData
                                            string childNodeName = parts[1];  // paramCode, paramName, etc.

                                            // 获取或创建父节点
                                            XmlNode parentNode = sendDataNode.SelectSingleNode(parentNodeName);
                                            if (parentNode == null)
                                            {
                                                parentNode = _mesParamOC.CreateElement(parentNodeName);
                                                sendDataNode.AppendChild(parentNode);
                                            }

                                            // 获取或创建 <item> 节点
                                            XmlNode itemNode;
                                            if (!itemNodes.ContainsKey(parentNodeName))
                                            {
                                                itemNode = _mesParamOC.CreateElement("item");
                                                parentNode.AppendChild(itemNode);
                                                itemNodes[parentNodeName] = itemNode;
                                            }
                                            else
                                            {
                                                itemNode = itemNodes[parentNodeName];
                                            }

                                            // 创建子节点并设置值
                                            XmlNode childNode = _mesParamOC.CreateElement(childNodeName);
                                            childNode.InnerText = paramValue;
                                            itemNode.AppendChild(childNode);
                                        }
                                        else
                                        {
                                            // 普通字段
                                            XmlNode paramNode = _mesParamOC.CreateElement(paramName);
                                            paramNode.InnerText = paramValue;
                                            sendDataNode.AppendChild(paramNode);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                // 保存修改后的 XML 文件
                string filePath = BasePath + "Config\\MesParamConfig.xml";
                _mesParamOC.Save(filePath);

                MessageBox.Show("数据保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存数据时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void UpdateXmlNode(XmlNode parentNode, string nodeName, string value)
        {
            XmlNode node = parentNode.SelectSingleNode(nodeName);
            if (node != null)
            {
                node.InnerText = value;
            }
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            try
            {
                CheckMesParamOC();
                LoadMesInterface();
                LoadXmlDataToAllDataGridViews();

                MessageBox.Show("数据加载成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private Dictionary<string, string> ConvertSendDataToJsonDictionary()
        {
            Dictionary<string, string> sendDataJsonDictionary = new Dictionary<string, string>();

            // 获取所有 MesModel 节点
            XmlNodeList mesModelNodes = _mesParamOC.SelectNodes("//MesModel");

            foreach (XmlNode mesModelNode in mesModelNodes)
            {
                // 获取 MesModel 的 name 属性
                string modelName = mesModelNode.Attributes["name"]?.Value;
                if (string.IsNullOrEmpty(modelName))
                {
                    continue;
                }

                // 获取 SendData 节点
                XmlNode sendDataNode = mesModelNode.SelectSingleNode("SendData");
                if (sendDataNode != null)
                {
                    // 将 SendData 节点转换为 JSON 字符串
                    string sendDataJson = XmlToJson(sendDataNode);

                    // 将 modelName 作为键，sendDataJson 作为值添加到字典中
                    sendDataJsonDictionary[modelName] = sendDataJson;
                }
            }

            return sendDataJsonDictionary;
        }
        private static string XmlToJson(XmlNode xmlNode)
        {
            // 直接使用 Newtonsoft.Json 将 XmlNode 转换为 JSON 字符串
            string json = JsonConvert.SerializeXmlNode(xmlNode, Newtonsoft.Json.Formatting.Indented);
            // 如果结果是包裹在根节点中的，去掉根节点
            if (json.StartsWith("{") && json.EndsWith("}"))
            {
                string nodeName = xmlNode.Name;
                int startIndex = json.IndexOf($"\"{nodeName}\":") + $"\"{nodeName}\":".Length;
                json = json.Substring(startIndex, json.Length - startIndex - 1);
            }
            return json;
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            int selectedIndex = tabControl1.SelectedIndex;
            //object model = null;

            switch (selectedIndex)
            {
                case 0:
                    LoginCheck_Model model = new LoginCheck_Model();
                    ProcessMesRequest(selectedIndex, model);
                    break;
                case 1:
                    GetSpecifications_Model model1 = new GetSpecifications_Model();
                    ProcessMesRequest(selectedIndex, model1);
                    break;
                case 2:
                    InStationCheck_Model model2 = new InStationCheck_Model();
                    ProcessMesRequest(selectedIndex, model2);
                    break;
                case 3:
                    GetTestData_Model model3 = new GetTestData_Model();
                    ProcessMesRequest(selectedIndex, model3);
                    break;
                case 4:
                    OutStationCheckData_Model model4 = new OutStationCheckData_Model();
                    model4.groupCode = "SubCapacity";
                    model4.deviceSn = "L2CAPAC019";
                    model4.timeStamp = "2018-01-01 10:10:00";
                    model4.operatorId = "63462";
                    model4.productSn = "06TCEA1N01L01H8310032761";
                    model4.moNumber = "Test20181218";
                    OutStationCheckData_Model.TestData[] testdatas = { new OutStationCheckData_Model.TestData { paramCode = "123", paramName = "3", paramValue = "4", paramResult = "5", paramUnit = "6" },
                     new OutStationCheckData_Model.TestData { paramCode = "sda", paramName = "sdasd", paramValue = "asd", paramResult = "fdf", paramUnit = "zxz" },
                     new OutStationCheckData_Model.TestData { paramCode = "gfdg", paramName = "dfgd", paramValue = "ret", paramResult = "yjy", paramUnit = "yrh" }};
                    model4.testData = testdatas;
                    OutStationCheckData_Model.Environment[] Environments = { new OutStationCheckData_Model.Environment { paramCode = "123", paramName = "3", paramValue = "4", paramResult = "5", paramUnit = "6" },
                     new OutStationCheckData_Model.Environment { paramCode = "sda", paramName = "sdasd", paramValue = "asd", paramResult = "fdf", paramUnit = "zxz" },
                     new OutStationCheckData_Model.Environment { paramCode = "gfdg", paramName = "dfgd", paramValue = "ret", paramResult = "yjy", paramUnit = "yrh" }};
                    model4.environment = Environments;
                    OutStationCheckData_Model.StepData[] StepDatas = { new OutStationCheckData_Model.StepData { trayNo = "123", channelNo = "3", batchNo = "4", step = "5", stepName = "6" },
                     new OutStationCheckData_Model.StepData { trayNo = "122223", channelNo = "3", batchNo = "4", step = "5", stepName = "6"  },
                     new OutStationCheckData_Model.StepData { trayNo = "1333323", channelNo = "3", batchNo = "4", step = "5", stepName = "6" }};
                    model4.stepData = StepDatas;

                    ProcessMesRequest(selectedIndex, model4);
                    break;
                case 5:
                    GetJellyrollOfAB_Model model5 = new GetJellyrollOfAB_Model();
                    ProcessMesRequest(selectedIndex, model5);
                    break;
                case 6:
                    SampleDataUpload_Model model6 = new SampleDataUpload_Model();
                    ProcessMesRequest(selectedIndex, model6);
                    break;
                case 7:
                    DeviceOperationAuthority_Model model7 = new DeviceOperationAuthority_Model();
                    ProcessMesRequest(selectedIndex, model7);
                    break;
                case 8:
                    getIPQCStatus_Model model8 = new getIPQCStatus_Model();
                    ProcessMesRequest(selectedIndex, model8);
                    break;
                default:
                    MessageBox.Show("未支持的选项卡索引");
                    return;
            }

        }

        /// <summary>
        /// MES主入口
        /// </summary>
        /// <param name="tabNo">选项卡索引</param>
        /// <param name="model">请求模型</param>
        /// <returns>返回处理结果</returns>
        public object ProcessMesRequest(int tabNo, object model)
        {
            object rtnCode = false;
            string strResponse = string.Empty;
            string strOutMessage = string.Empty;
            TextBoxReply.Text = "";
            try
            {
                switch (tabNo)
                {
                    case 0:
                        if (model is LoginCheck_Model loginCheckModel)
                        {
                            rtnCode = MesEntity.LoginCheck(loginCheckModel, out strResponse, out strOutMessage);
                        }
                        else
                        {
                            throw new InvalidCastException("模型类型不匹配：预期为 LoginCheck_Model");
                        }
                        break;
                    case 1:
                        if (model is GetSpecifications_Model getSpecificationsModel)
                        {
                            rtnCode = MesEntity.GetSpecifications(getSpecificationsModel, out strResponse, out strOutMessage);
                        }
                        else
                        {
                            throw new InvalidCastException("模型类型不匹配：预期为 GetSpecifications_Model");
                        }
                        break;
                    case 2:
                        if (model is InStationCheck_Model inStationCheckModel)
                        {
                            rtnCode = MesEntity.InStationCheck(inStationCheckModel, out strResponse, out strOutMessage);
                        }
                        else
                        {
                            throw new InvalidCastException("模型类型不匹配：预期为 InStationCheck_Model");
                        }
                        break;
                    case 3:                        
                        if (model is GetTestData_Model getTestDataModel)
                        {
                            rtnCode = MesEntity.GetTestData(getTestDataModel, out strResponse, out strOutMessage);
                        }
                        else
                        {
                            throw new InvalidCastException("模型类型不匹配：预期为 GetTestData_Model");
                        }
                        break;
                    case 4:
                        if (model is OutStationCheckData_Model outStationCheckDataModel)
                        {
                            rtnCode = MesEntity.OutStationCheckData(outStationCheckDataModel, out strResponse, out strOutMessage);
                        }
                        else
                        {
                            throw new InvalidCastException("模型类型不匹配：预期为 OutStationCheckData_Model");
                        }
                        break;
                    case 5:
                        if (model is GetJellyrollOfAB_Model getJellyrollOfABModel)
                        {
                            rtnCode = MesEntity.GetJellyrollOfAB(getJellyrollOfABModel, out strResponse, out strOutMessage);
                        }
                        else
                        {
                            throw new InvalidCastException("模型类型不匹配：预期为 GetJellyrollOfAB_Model");
                        }
                        break;                    
                    case 6:
                        if (model is SampleDataUpload_Model sampleDataUploadModel)
                        {
                            rtnCode = MesEntity.SampleDataUpload(sampleDataUploadModel, out strResponse, out strOutMessage);
                        }
                        else
                        {
                            throw new InvalidCastException("模型类型不匹配：预期为 SampleDataUpload_Model");
                        }
                        break;
                    case 7:
                        if (model is DeviceOperationAuthority_Model deviceOperationAuthorityModel)
                        {
                            rtnCode = MesEntity.DeviceOperationAuthority(deviceOperationAuthorityModel, out strResponse, out strOutMessage);
                        }
                        else
                        {
                            throw new InvalidCastException("模型类型不匹配：预期为 DeviceOperationAuthority_Model");
                        }
                        break;
                    case 8:
                        if (model is getIPQCStatus_Model getIPQCStatusModel)
                        {
                            rtnCode = MesEntity.getIPQCStatus(getIPQCStatusModel, out strResponse, out strOutMessage);
                        }
                        else
                        {
                            throw new InvalidCastException("模型类型不匹配：预期为 getIPQCStatus_Model");
                        }
                        break;
                    default:
                        throw new ArgumentOutOfRangeException(nameof(tabNo), "未支持的选项卡索引");
                }
                TextBoxReply.Text = strResponse;
            }
            catch (Exception ex)
            {
                TextBoxReply.Text = $"Error: {ex.Message}";
                rtnCode = false;
            }

            return rtnCode;
        }
        private void btnlogin_Click(object sender, EventArgs e)
        {
            LoginCheck_Model model = new LoginCheck_Model();
            model.userNo = txtEquipPC_ID.Text;
            model.passWord = txtEquip_PassWord.Text;

            ProcessMesRequest(0, model);
        }
    }
}